//
//  SATransferDetailViewController.m
//  SAP
//
//  Created by 中矿科技有限公司 on 17/9/14.
//  Copyright © 2017年 中矿科技有限公司. All rights reserved.
//

#import "SATransferDetailViewController.h"
#import "AgreeViewController.h"
#import "SATransfertSearchViewController.h"
#import "SAProvisionViewController.h"

#import "ActionFlowCell.h"
#import "SATransferDetailModel.h"

#import "NSString+getDateTime.h"

@interface SATransferDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)UIView * viewBtn;

@end

static NSString *const actionCellID =@"ActionFlowCell";
@implementation SATransferDetailViewController
{
    AFHTTPData *_http;
    NSMutableArray *_sourceData;//流程列表
    NSMutableArray *_actionList;//按钮列表
    NSMutableArray *_nextNodeUserList;
    
    MBProgressHUD *_waitHud;
    SATransferDetailModel *_sourceModel;//详情数据
    NSDictionary *_detailDict;
    
    UIView *_viewBtn;
}

-(UITableView *)tableView{
    if (_tableView) {
        return _tableView;
    }
    _tableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-8) style:UITableViewStyleGrouped];
    _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
    [_tableView registerNib:[UINib nibWithNibName:@"ActionFlowCell" bundle:nil] forCellReuseIdentifier:actionCellID];
    _tableView.showsVerticalScrollIndicator =NO;
    _tableView.showsHorizontalScrollIndicator =NO;
    _tableView.delegate =self;
    _tableView.dataSource =self;
    return _tableView;
}
-(UIView *)viewBtn{
    if (!_viewBtn) {
        _viewBtn=[[UIView alloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT-44-64 , SCREEN_WIDTH, 44)];
        [self.view addSubview:_viewBtn];
    }
    return _viewBtn;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _dataArray =[[NSMutableArray alloc]init];
    _actionList =[[NSMutableArray alloc]init];
    _nextNodeUserList =[[NSMutableArray alloc]init];
    _http =[[AFHTTPData alloc]init];
    _sourceData =[[NSMutableArray alloc]init];
    
    [_dataArray addObjectsFromArray: @[@"基本信息",@"关联合同",@"备注",@"操作流程"]];
    
    [self customUI];
    [self prepareData];
}

-(void)customUI{
    self.view.backgroundColor =SA_AllBackColor;
    self.navigationItem.title =@"调拨详情";
    
    [self.view addSubview:self.tableView];
}



-(void)prepareData{
    if(!_waitHud)_waitHud=[[MBProgressHUD alloc] initWithView:self.view];//加载
    [self.view addSubview:_waitHud];
    // _waitHud.mode = MBProgressHUDModeText;
    [_waitHud showAnimated:YES];
    NSString *strUrl =[NSString stringWithFormat:SAPTransferDetailKUrl,self.controllerId];
    [_http postTokenDataWithUrl:strUrl httpBobyData:nil onSuccess:^(NSData *data) {
        
        _detailDict =[ConstractDetailModel getGetOptionsDetailDictfromData:data];
        
        _sourceModel =[SATransferDetailModel getTransferDetailfromData:data];
        
        NSArray *array =[SAflowInstanceHistoryList getOptionsFlowDetailfromData:data];
        [_sourceData removeAllObjects];
        [_sourceData addObjectsFromArray:array];
        
        NSArray *array1 =[SAActionList getOptionsAcstionListfromData:data];
        [_actionList removeAllObjects];
        [_actionList addObjectsFromArray:array1];
        
        NSArray *array2 =[SANextNodeUserList getOptionsNextNodeUserListfromData:data];
        [_nextNodeUserList addObjectsFromArray:array2];
        //判断是否显示删除按钮
        if ( [[[UserManager sharedInstance] getUserId].description isEqualToString:_sourceModel.userId.description]) {
            if (_sourceModel.status.integerValue ==1 || _sourceModel.status.integerValue ==3) {
                [self creatRightItem];
            }else{
                self.navigationItem.rightBarButtonItem =nil;
            }
        }

        if(_actionList.count>0 )[self creatBtn];
        if (_actionList.count ==0 ) {
            self.tableView.frame =CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64);
            [_viewBtn removeFromSuperview];
        }
        [_tableView reloadData];
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:YES];
    } onFailure:^(NSError *error) {
        [_waitHud showAnimated:NO];
        [_waitHud hideAnimated:YES];
    }];
}


-(void)onClickedBtn:(UIButton *)sender{
    NSString *actionCode;
    NSString *nextUserID =@"0";
    if(_nextNodeUserList.count>0) nextUserID =[_nextNodeUserList[0] Id];
    for (SAActionList *model in _actionList) {
        if ([model.actionName isEqualToString:sender.titleLabel.text]) {
            actionCode =model.actionCode;
        }
    }
    AgreeViewController *agreeVC=[[AgreeViewController alloc]init];
    agreeVC.SAApprovalStatusType =SAApprovalTransfer;
    agreeVC.completion =^(id userInfo, AgreeViewController *bVC){
        [self prepareData];
    };
    agreeVC.nextNodeUserList =_nextNodeUserList;
    agreeVC.actionCode =actionCode;
   // agreeVC.nextUserID =nextUserID;
    agreeVC.detailDict =_detailDict;
    agreeVC.navtitle =sender.titleLabel.text;
    
    
    [self.navigationController pushViewController:agreeVC animated:NO];
    
#if 0
    NSString *strUrl =[NSString stringWithFormat:SAPExecuteActionKUrl,actionCode,nextUserID,@""];
    [_http postTokenDataWithUrl:strUrl httpBobyData:_detailDict onSuccess:^(NSData *data) {
        
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dict);
        [MBProgressHUD showSuccess:[NSString stringWithFormat:@"合同%@成功",sender.titleLabel.text]];
        !self.completion ?: self.completion(nil, self);
        [self.navigationController popViewControllerAnimated:NO];
    } onFailure:^(NSError *error) {
        [MBProgressHUD showSuccess:[NSString stringWithFormat:@"合同%@失败",sender.titleLabel.text]];
    }];
#endif
    
}

-(void)creatRightItem{
    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(onClickedDelItem)];
}

-(void)creatBtn{
    float btnHight =0;
    float btnwight =SCREEN_WIDTH/_actionList.count;
//    if (_sourceModel.status.integerValue ==1) {
//        UIButton *submitBtn =[UITool btnWithTitle:[_actionList[1] actionName] frame:CGRectMake(0,btnHight, SCREEN_WIDTH,44) font:[UIFont systemFontOfSize:17] unselectColor:[UIColor colorFromHex:@"333333"] backColor:[UIColor whiteColor]];
//        [submitBtn addTarget:self action:@selector(onClickedBtn:) forControlEvents:UIControlEventTouchUpInside];
//        [self.viewBtn addSubview:submitBtn];
//        return;
//    }
    
    for (NSInteger i =0; i<_actionList.count; i++) {
        
        
        if([[_actionList[i] actionCode] isEqualToString:@"TransferFlow.Apply.Save"]) continue;
        if ([[_actionList[i] actionCode] isEqualToString:@"TransferFlow.Apply.Apply"] ) {
            UIButton *submitBtn =[UITool btnWithTitle:[_actionList[i] actionName] frame:CGRectMake(0,btnHight, SCREEN_WIDTH,44) font:[UIFont systemFontOfSize:17] unselectColor:[UIColor colorFromHex:@"333333"] backColor:[UIColor whiteColor]];
            [submitBtn addTarget:self action:@selector(onClickedBtn:) forControlEvents:UIControlEventTouchUpInside];
            [self.viewBtn addSubview:submitBtn];
            return;
        }
        
        UIButton *submitBtn =[UITool btnWithTitle:[_actionList[i] actionName] frame:CGRectMake(btnwight*i,btnHight, btnwight,44) font:[UIFont systemFontOfSize:17] unselectColor:[UIColor colorFromHex:@"333333"] backColor:[UIColor whiteColor]];
        [submitBtn addTarget:self action:@selector(onClickedBtn:) forControlEvents:UIControlEventTouchUpInside];
        [self.viewBtn addSubview:submitBtn];
    }
}


-(void)onClickedDelItem{
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"删除" message:@"确定删除该调拨" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *str =[NSString stringWithFormat:SAPTransferDeleteKUrl,_sourceModel.Id];
        [_http getDataWithUrl:str onSuccess:^(NSData *data) {
            NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dict);
            [MBProgressHUD showSuccess:@"调拨删除成功"];
            !self.completion ?: self.completion(nil, self);
            [self.navigationController popViewControllerAnimated:NO];
        } onFailure:^(NSError *error) {
            [MBProgressHUD showSuccess:@"调拨删除失败"];
        }];
    }];
    UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        //  NSLog(@"点击了取消");
    }];
    
    [alertVC addAction:OKAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}



#pragma mark tableView-Delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section ==0) {
        return 7;
    }else if (section ==1){
        return 3;
    }else if (section ==2){
        return 1;
    }else if (section ==3){
        return _sourceData.count;
    }
    return _sourceData.count;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    UILabel *label =[[UILabel alloc]initWithFrame:CGRectMake(15, 0, SCREEN_WIDTH, 44)];
    label.backgroundColor =SA_AllBackColor;
    label.textColor =[UIColor colorFromHex:@"333333"];
    label.text =_dataArray[section];
    [headView addSubview:label];
    return headView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==3) {
        return 80;
    }else if(indexPath.section ==2){
        CGFloat  remarkHeight =[_sourceModel.remark heightWithWidth:SCREEN_WIDTH-30 font:15];
        return remarkHeight <40 ? 40 : remarkHeight+10;
    }else{
        return 40;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section<3 ) {
        UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cellID"];
        if (!cell) {
            cell =[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellID"];
        }
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        cell.textLabel.textColor =[UIColor colorFromHex:@"666666"];
        //基本信息
        if (indexPath.section == 0) {
            if(indexPath.row ==0) cell.textLabel.text =[NSString stringWithFormat:@"供货单位: %@",_sourceModel.senderName];
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"收货单位: %@",_sourceModel.receiptorName];
            if(indexPath.row ==2) cell.textLabel.text =[NSString stringWithFormat:@"调拨单编号 : %@",_sourceModel.transferCode];
            if(indexPath.row ==3) cell.textLabel.text =[NSString stringWithFormat:@"调拨单有效日期: %@",_sourceModel.vaildStartorEndtime];
            if(indexPath.row ==4) cell.textLabel.text =[NSString stringWithFormat:@"品种: %@",_sourceModel.varietyName];
            if(indexPath.row ==5) cell.textLabel.text =[NSString stringWithFormat:@"煤种: %@",_sourceModel.coalTypeName];
            if(indexPath.row ==6) cell.textLabel.text =[NSString stringWithFormat:@"调拨量: %@",_sourceModel.totalNumberUnitName];
//            if(indexPath.row ==7) cell.textLabel.text =[NSString stringWithFormat:@"产品质量: %@",_sourceModel.productQuality];
            }
        if (indexPath.section == 1){
            if(indexPath.row ==0) cell.textLabel.text =[NSString stringWithFormat:@"合同编号: %@",_sourceModel.contractCode];
            if(indexPath.row ==1) cell.textLabel.text =[NSString stringWithFormat:@"出卖人: %@",_sourceModel.seller];
            if(indexPath.row ==2) cell.textLabel.text =[NSString stringWithFormat:@"收买人: %@",_sourceModel.buyer];
        }
        if (indexPath.section == 2){
            cell.textLabel.numberOfLines =0;
            cell.textLabel.text =[NSString stringWithFormat:@"  %@",_sourceModel.remark];
        }
        return cell;
    }else{
        ActionFlowCell *cell =[tableView dequeueReusableCellWithIdentifier:actionCellID forIndexPath:indexPath];
        [cell setFromContractTermsModel:_sourceData[indexPath.row]];
        cell.selectionStyle =UITableViewCellSelectionStyleNone;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==_dataArray.count-1) {
        SAProvisionViewController * provsionVC =[[SAProvisionViewController alloc]initWithNibName:@"SAProvisionViewController" bundle:nil];
        provsionVC.provisionStr =[NSString stringWithFormat:@"备注:\n\t%@", [_sourceData[indexPath.row] remark] ?[_sourceData[indexPath.row] remark]:@"" ];
        provsionVC.navTitle =[_sourceData[indexPath.row] nodeDisplayName];
        [self.navigationController pushViewController:provsionVC animated:NO];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
